package com.yylending.las.authority.register;

import android.text.TextUtils;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Model;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yyfax.infrastructure.mvp.ResponseCode;
import com.yylending.las.Global;
import com.yylending.las.authority.rsa.RSAEncodePresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by HenryZhang on 2016/11/3.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class RegisterPresenter extends RSAEncodePresenter<Model, RegisterPresenter.View> {
	private final static String TAG = "RegisterPresenter";

	public static class Generator implements PresenterFactory<RegisterPresenter> {
		@Override
		public RegisterPresenter create() {
			return new RegisterPresenter();
		}
	}

	public interface View extends IView {
		void registerSuccess();

		void registerFail(String retCode, String msg);

		void registerRetCode(String retCode);
	}

	private View mView;
	private String mRequestPage;

	@Override
	public void attach(RegisterPresenter.View view) {
		mRequestPage = view.getClass().getName();
		mView = view;
		mModel = new RegisterModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		return params;
	}

	public void register(String code, String phone, String pwd, String longitude, String latitude) {
		execute(new RegisterModel.RegisterAccount(phone, pwd, code, longitude, latitude), RegisterModel.METHOD_REGISTER, false, null, mRequestPage);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void registerResult(RegisterModel.RegisterResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			if (BaseResultEntity.isResponseSuccess(result)) {
				CLog.i(TAG, "注册成功");
				mView.registerSuccess();
			} else {
				String msg = result.getRetMsg();
				if (ResponseCode.CODE_DECODE_FAIL.equalsIgnoreCase(result.getRetCode())) {
					Global.KEY_RSA = "";
					msg = "注册失败，请重试";
				}
				mView.registerFail(result.getRetCode(), TextUtils.isEmpty(msg) ? "注册失败，请重试" : msg);
			}
			mView.registerRetCode(result.getRetCode());
		}
	}
}
